package middleware

import (
	"doctor-medicine-system/api/internal/types"
	"doctor-medicine-system/pkg"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation

		token := r.Header.Get("token")
		if token == "" {
			response := types.Response{
				Message: "token不能为空",
				Code:    500,
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, response)
			return
		}
		getToken, err := pkg.GetToken(token)
		if err != nil {
			response := types.Response{
				Message: err.Error(),
				Code:    500,
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, response)
			return
		}
		r.ParseForm()
		r.Form.Set("doctorId", getToken["doctorId"].(string))

		// Passthrough to next handler if need
		next(w, r)
	}
}
